package med.movyzer.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFileChooser;

import med.movyzer.io.GT3XData;

@SuppressWarnings("serial")
public class MovyzerFileChooserPreviewComponentGT3X extends JComponent implements PropertyChangeListener {

	protected File selectedFile;
	public URL success = this.getClass().getResource("/med/movyzer/gui/gfx/movyzer_menulogo_145x65.png");
	public URL error = this.getClass().getResource("/med/movyzer/gui/gfx/movyzer_menulogo_145x65error.png");

	public MovyzerFileChooserPreviewComponentGT3X(JFileChooser fc) {
		setPreferredSize(new Dimension(145, 200));
		fc.addPropertyChangeListener(this);
	}

	public void propertyChange(PropertyChangeEvent e) {

		String prop = e.getPropertyName();

		if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
			selectedFile = (File) e.getNewValue();
			repaint();
		}
	}

	protected void paintComponent(Graphics g) {

		int logo_distance=65;
		int line_height=12;
		int line_distance=12;

		super.paintComponent(g);
		g.setFont(new Font("sansserif", Font.BOLD, 12));
		g.drawString("Movyzer Filepreview:", line_distance, logo_distance + line_height);
		g.setFont(new Font("sansserif", Font.PLAIN, 12));

		if (selectedFile != null){

			try {
				int movementCount=GT3XData.preview(selectedFile.getPath());
				success(g, success);
				g.drawString("Detected GT3X file!", line_distance, logo_distance + 3*line_height);
				g.drawString("This File contains:", line_distance, logo_distance + 5*line_height);
				g.drawString(movementCount+" movements", line_distance, logo_distance + 6*line_height);
			} catch (Exception e) {
				error(g, error);
				g.setColor(Color.RED.darker());
				g.drawString("Cannot read this file.", line_distance, logo_distance + 3*line_height);
			}
		}
		else{
			error(g, error);
			g.setColor(Color.RED.darker());
			g.drawString("No file selected.", line_distance, logo_distance + 3*line_height);
		}
	}

	public void success(Graphics g, URL u){
		BufferedImage img;
		try {
			img = ImageIO.read(u);
			g.drawImage(img, 0, 0, 145, 65, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void error(Graphics g, URL u){
		BufferedImage img;
		try {
			img = ImageIO.read(u);
			g.drawImage(img, 0, 0, 145, 65, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
